﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathLib {
    public class Gauss {


        private static Random rnd = new Random();


        public double NextGaussian(double a, double sigma) {
            bool haveNextNextGaussian = false;
            double nextNextGaussian = 0;


            if (haveNextNextGaussian) {
                haveNextNextGaussian = false;
                return nextNextGaussian;
            } else {
                double v1, v2, s;
                do {
                    v1 = 2 * rnd.NextDouble() - 1;   // between -1.0 and 1.0
                    v2 = 2 * rnd.NextDouble() - 1;   // between -1.0 and 1.0
                    s = v1 * v1 + v2 * v2;
                } while (s >= 1 || s == 0);
                double multiplier = Math.Sqrt(-2 * Math.Log(s) / s);
                nextNextGaussian = v2 * multiplier;
                haveNextNextGaussian = true;
                double z = a + sigma * v1 * multiplier;
                return z;
            }
        }
    }
}